package com.bawei.module_vehicle.ui

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.module_vehicle.model.CarModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class CarViewModel @Inject constructor(
    private val repository: CarRepository
) : ViewModel() {

    // 存储单个车辆数据（默认空）
    private val _car = MutableStateFlow<CarModel?>(null)
    val car = _car.asStateFlow()

    // 加载状态
    private val _uiState = MutableStateFlow<UiState>(UiState.Idle)
    val uiState = _uiState.asStateFlow()

    // 发起搜索（根据 id）
    fun searchVehicleById(id: Long) {
        _uiState.value = UiState.Loading
        viewModelScope.launch {
            repository.searchVehicleById(id)
                .catch { e ->
                    _uiState.value = UiState.Failed(e.message ?: "查询失败")
                }
                .collect { response ->
                    if (response.code==200) { // 假设 BaseResponse 有 isSuccess 判断
                        _car.value = response.data
                        _uiState.value = UiState.Success
                    } else {
                        _uiState.value = UiState.Failed(response.message ?: "请求失败")
                    }
                }
        }
    }

    // 加载状态密封类
    sealed class UiState {
        object Idle : UiState()
        object Loading : UiState()
        object Success : UiState()
        data class Failed(val errorMsg: String) : UiState()
    }
}